import React, { useState } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Grid,
  Chip,
  Alert,
  Paper,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Snackbar,
  IconButton,
  Stack,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  FormHelperText,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';

interface Skill {
  id: number;
  name: string;
  proficiency: number; // 1: 入门, 2: 基本, 3: 精通
  description?: string;
  user_id: number;
}

interface SkillsProps {
  skills: Skill[];
  onUpdate: () => void;
}

// 技能熟练度映射
const proficiencyMap = {
  1: { label: '入门', color: 'info' },
  2: { label: '基本', color: 'success' },
  3: { label: '精通', color: 'error' },
};

const Skills: React.FC<SkillsProps> = ({ skills, onUpdate }) => {
  const [open, setOpen] = useState(false);
  const [editingSkill, setEditingSkill] = useState<Skill | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    proficiency: 1,
    description: '',
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);

  const resetForm = () => {
    setFormData({
      name: '',
      proficiency: 1,
      description: '',
    });
    setEditingSkill(null);
    setError('');
  };

  const handleOpenDialog = (skill?: Skill) => {
    if (skill) {
      setEditingSkill(skill);
      setFormData({
        name: skill.name,
        proficiency: skill.proficiency,
        description: skill.description || '',
      });
    } else {
      resetForm();
    }
    setOpen(true);
  };

  const handleCloseDialog = () => {
    setOpen(false);
    resetForm();
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSelectChange = (e: any) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async () => {
    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      if (!formData.name.trim()) {
        throw new Error('技能名称不能为空');
      }

      const url = editingSkill 
        ? `/api/user/skills/${editingSkill.id}` 
        : '/api/user/skills';

      const method = editingSkill ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(formData)
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '保存技能失败');
      }

      setSuccessMessage(editingSkill ? '技能更新成功' : '技能添加成功');
      setSuccess(true);
      handleCloseDialog();
      onUpdate(); // 通知父组件更新数据
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    setDeletingId(id);
    setDeleteConfirmOpen(true);
  };

  const confirmDelete = async () => {
    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      const response = await fetch(`/api/user/skills/${deletingId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || '删除技能失败');
      }

      setSuccessMessage('技能删除成功');
      setSuccess(true);
      setDeleteConfirmOpen(false);
      onUpdate(); // 通知父组件更新数据
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
      setDeletingId(null);
    }
  };

  return (
    <Box sx={{ py: 2 }}>
      <Snackbar 
        open={success} 
        autoHideDuration={3000} 
        onClose={() => setSuccess(false)} 
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="success" onClose={() => setSuccess(false)}>
          {successMessage}
        </Alert>
      </Snackbar>

      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h5" component="h2">专业技能</Typography>
        <Button 
          startIcon={<AddIcon />} 
          variant="contained" 
          color="primary"
          onClick={() => handleOpenDialog()}
        >
          添加技能
        </Button>
      </Box>

      {error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}

      {skills.length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 4 }}>
          <Typography variant="body1" color="textSecondary">
            暂无技能，点击"添加技能"按钮开始添加
          </Typography>
        </Box>
      ) : (
        <Paper elevation={1} sx={{ p: 3 }}>
          <Grid container spacing={2}>
            {skills.map((skill) => (
              <Grid item key={skill.id} xs={12} sm={6} md={4}>
                <Box sx={{ 
                  border: '1px solid #e0e0e0', 
                  borderRadius: 1, 
                  p: 2,
                  display: 'flex',
                  flexDirection: 'column',
                  height: '100%'
                }}>
                  <Box sx={{ 
                    display: 'flex', 
                    justifyContent: 'space-between', 
                    alignItems: 'center',
                    mb: 1
                  }}>
                    <Typography variant="h6" component="h3">
                      {skill.name}
                    </Typography>
                    <Box>
                      <IconButton 
                        size="small" 
                        color="primary"
                        onClick={() => handleOpenDialog(skill)}
                      >
                        <EditIcon fontSize="small" />
                      </IconButton>
                      <IconButton 
                        size="small" 
                        color="error"
                        onClick={() => handleDelete(skill.id)}
                      >
                        <DeleteIcon fontSize="small" />
                      </IconButton>
                    </Box>
                  </Box>
                  
                  <Box sx={{ mt: 1, mb: 2 }}>
                    <Chip 
                      label={proficiencyMap[skill.proficiency as 1 | 2 | 3]?.label || '未知'} 
                      color={proficiencyMap[skill.proficiency as 1 | 2 | 3]?.color as any || 'default'} 
                      size="small" 
                      sx={{ mr: 1 }}
                    />
                  </Box>
                  
                  {skill.description && (
                    <Typography variant="body2" color="text.secondary" sx={{ mt: 'auto' }}>
                      {skill.description}
                    </Typography>
                  )}
                </Box>
              </Grid>
            ))}
          </Grid>
        </Paper>
      )}

      {/* 添加/编辑技能对话框 */}
      <Dialog 
        open={open} 
        onClose={handleCloseDialog}
        fullWidth
        maxWidth="sm"
      >
        <DialogTitle>
          {editingSkill ? '编辑技能' : '添加技能'}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 1 }}>
            {error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}
            
            <Grid container spacing={2}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="技能名称"
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  required
                  placeholder="例如：JavaScript, Python, 数据分析"
                  variant="outlined"
                />
              </Grid>
              
              <Grid item xs={12}>
                <FormControl fullWidth variant="outlined">
                  <InputLabel id="proficiency-label">熟练程度</InputLabel>
                  <Select
                    labelId="proficiency-label"
                    name="proficiency"
                    value={formData.proficiency}
                    onChange={handleSelectChange}
                    label="熟练程度"
                  >
                    <MenuItem value={1}>入门</MenuItem>
                    <MenuItem value={2}>基本</MenuItem>
                    <MenuItem value={3}>精通</MenuItem>
                  </Select>
                  <FormHelperText>选择您对该技能的熟练程度</FormHelperText>
                </FormControl>
              </Grid>
              
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="技能描述"
                  name="description"
                  value={formData.description}
                  onChange={handleChange}
                  placeholder="描述您的技能掌握情况、相关项目经验等"
                  multiline
                  rows={3}
                  variant="outlined"
                />
              </Grid>
            </Grid>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog} disabled={loading}>取消</Button>
          <Button 
            onClick={handleSubmit} 
            variant="contained" 
            color="primary"
            disabled={loading || !formData.name.trim()}
          >
            {loading ? '保存中...' : '保存'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteConfirmOpen}
        onClose={() => setDeleteConfirmOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>确定要删除此技能吗？此操作不可撤销。</Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteConfirmOpen(false)} disabled={loading}>取消</Button>
          <Button 
            onClick={confirmDelete} 
            color="error"
            disabled={loading}
          >
            {loading ? '删除中...' : '删除'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default Skills; 